package com.redwine.app;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.adapter.BannerViewPager;
import com.redwine.app.adapter.SupplyOfGoodsDetailAdapter;
import com.redwine.app.chat.ChatActivity;
import com.redwine.app.chat.ChatConstant;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.AdoptDetailResponse;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.CommonListDataResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.DimenUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.view.AlertDialog;
import com.redwine.app.view.EmptyView;
import com.redwine.app.view.MeasureListView;
import com.redwine.app.view.shareDialog.BottomDialog;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 货源详情
 * 作者：gassion on 17/8/23 23:02
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class PublishedSourcesDetailActivity extends BaseActivity {

    @ViewInject(R.id.main_banner_Layout)
    private BannerViewPager goodsBannerLayout;
    @ViewInject(R.id.view_feed_banner_inner)
    private RelativeLayout viewFeedBannerInner;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    @ViewInject(R.id.layout_right_share)
    private LinearLayout mRightShare;
    @ViewInject(R.id.supply_of_goods_tv_collect)
    private TextView supplyOfGoodsTvCollect;
    @ViewInject(R.id.supply_of_goods_tv_send_time)
    private TextView supplyOfGoodsTvSendTime;
    @ViewInject(R.id.supply_of_goods_tv_shop_name)
    private TextView supplyOfGoodsTvShopName;
    @ViewInject(R.id.supply_of_goods_tv_content)
    private TextView supplyOfGoodsTvContent;
    @ViewInject(R.id.supply_of_goods_tv_shop_price)
    private TextView supplyOfGoodsTvShopPrice;
    @ViewInject(R.id.supply_of_goods_iv_pic)
    private ImageView supplyOfGoodsIvPic;
    @ViewInject(R.id.supply_of_goods_tv_name)
    private TextView supplyOfGoodsTvName;
    @ViewInject(R.id.supply_of_goods_tv_phone)
    private TextView supplyOfGoodsTvPhone;
    @ViewInject(R.id.supply_of_goods_tv_address)
    private TextView supplyOfGoodsTvAddress;
    @ViewInject(R.id.supply_of_goods_tv_comments)
    private TextView supplyOfGoodsTvComments;
    @ViewInject(R.id.supply_of_goods_measure_list_view)
    private MeasureListView supplyOfGoodsMeasureListView;
    @ViewInject(R.id.supply_of_goods_ll_offer_comments)
    private LinearLayout supplyOfGoodsLlOfferComments;
    @ViewInject(R.id.published_sources_all_layout)
    private LinearLayout publishedSourcesAllLayout;
    @ViewInject(R.id.empty_view)
    private EmptyView emptyView;
    @ViewInject(R.id.supply_of_goods_tv_send_message)
    private TextView mTvMessage;
    @ViewInject(R.id.supply_of_goods_tv_leave_a_message)
    private TextView mTvLeaveMessage;
    private SupplyOfGoodsDetailAdapter supplyOfGoodsDetailAdapter;
    private View view;
    private AdoptDetailResponse.DataEntity mResponseData;
    private AdoptDetailResponse.DataEntity.PublishInfoEntity publish_info;
    private AdoptDetailResponse.DataEntity.SupplierInfoEntity supplier_info;
    public static final String SHOP_NAME = "SHOP_NAME";
    public static final String SHOP_UID = "SHOP_UID";
    public static final String SHOP_ID = "SHOP_ID";
    private String mName;
    private String mUid;
    private String mId;
    private Intent intent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(this).inflate(R.layout.activity_published_sources, null);
        setContentView(view);
        ViewUtils.inject(this, view);
        initView();
        requestData();
    }

    private void initView() {
        Intent intent = getIntent();
        if (null != intent) {
            mName = getIntent().getStringExtra(SHOP_NAME);
            mUid = getIntent().getStringExtra(SHOP_UID);
            mId = getIntent().getStringExtra(SHOP_ID);
        } else {
            finish();
        }
        headerTitle.setText(mName);
        mRightShare.setVisibility(View.VISIBLE);
        layoutBack.setVisibility(View.VISIBLE);
        supplyOfGoodsDetailAdapter = new SupplyOfGoodsDetailAdapter(this);
        supplyOfGoodsMeasureListView.setAdapter(supplyOfGoodsDetailAdapter);
        supplyOfGoodsMeasureListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //GASSION 留言板item点击
            }
        });
    }

    public void requestData() {
        if (!NetUtil.checkNet(this)) {
            showToast(R.string.generic_check);
            setErrorView(emptyView, null);
            return;
        }

        showWaiting();
        String url = NetworkConstants.ADOPT_DETAIL_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("publish_uid", mUid);
        params.put("publish_id", mId);
        GsonRequest<AdoptDetailResponse> request = new GsonRequest<>(url, Request.Method.POST,
                AdoptDetailResponse.class, false, params, new Response.Listener<AdoptDetailResponse>() {
            @Override
            public void onResponse(AdoptDetailResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    mResponseData = response.getData();
                    updateView(mResponseData);
                } else {
                    dismissWaiting();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                setEmptyView(emptyView, null);
                showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 更新view
     *
     * @param responseData
     */
    private void updateView(AdoptDetailResponse.DataEntity responseData) {
        if (null == responseData) {
            setEmptyView(emptyView, null);
            return;
        }

        try {
            publishedSourcesAllLayout.setVisibility(View.VISIBLE);
            updateCollectUI(responseData);
            List<String> stringList = super.strConvertList(responseData.getPublish_info().getPic());
            if (!stringList.isEmpty()) {
                updateBannerView(stringList);
            }
            publish_info = responseData.getPublish_info();
            headerTitle.setText(publish_info.getName());
            supplyOfGoodsTvShopName.setText(publish_info.getName());
            supplyOfGoodsTvContent.setText(publish_info.getContent());
            supplyOfGoodsTvShopPrice.setText(publish_info.getPrice());
            supplyOfGoodsTvSendTime.setText(publish_info.getRemain_before());
            supplier_info = responseData.getSupplier_info();
            BitmapUtils.loadImage(supplyOfGoodsIvPic, supplier_info.getAvatar(), BitmapUtils.THE_ARTICLE);
            supplyOfGoodsTvName.setText(supplier_info.getName());
            if (supplier_info.getSex()) {
                supplyOfGoodsTvName.setCompoundDrawables(null, null, getIdDrawable(R.mipmap.icon_male), null);
            } else {
                supplyOfGoodsTvName.setCompoundDrawables(null, null, getIdDrawable(R.mipmap.icon_female), null);
            }
            supplyOfGoodsTvPhone.setText(supplier_info.getMobile());
            supplyOfGoodsTvAddress.setText(supplier_info.getTitle());
            if (Global.user.getUid().equals(supplier_info.getUid())) {
                mTvMessage.setTextColor(getResources().getColor(R.color.color_7f7f7f));
                mTvMessage.setBackgroundResource(R.drawable.gray_shape);
                mTvLeaveMessage.setBackgroundResource(R.drawable.gray_shape);
                mTvLeaveMessage.setTextColor(getResources().getColor(R.color.color_7f7f7f));
                mTvMessage.setEnabled(false);
                mTvLeaveMessage.setEnabled(false);
            } else {
                mTvMessage.setBackgroundResource(R.drawable.common_shape_select);
                mTvMessage.setTextColor(getResources().getColor(R.color.white));
                mTvLeaveMessage.setBackgroundResource(R.drawable.common_shape_select);
                mTvLeaveMessage.setTextColor(getResources().getColor(R.color.white));
                mTvMessage.setEnabled(true);
                mTvLeaveMessage.setEnabled(true);
            }

            List<AdoptDetailResponse.DataEntity.MessageEntity> responseDataMessage = responseData.getMessage();
            if (null != responseDataMessage && !responseDataMessage.isEmpty()) {
                supplyOfGoodsLlOfferComments.setVisibility(View.VISIBLE);
                supplyOfGoodsTvComments.setText(String.valueOf(responseDataMessage.size()));
                supplyOfGoodsDetailAdapter.setData(responseDataMessage);
            } else {
                supplyOfGoodsLlOfferComments.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            setEmptyView(emptyView, null);
            e.printStackTrace();
        }

    }

    /**
     * 更新ui是否收藏
     *
     * @param responseData
     */
    private void updateCollectUI(AdoptDetailResponse.DataEntity responseData) {
        if (responseData.isCollection()) {
            //已收藏
            supplyOfGoodsTvCollect.setText(R.string.already_collected);
            supplyOfGoodsTvCollect.setCompoundDrawables(getIdDrawable(R.mipmap.icon_collect_select), null, null, null);
        } else {
            //未收藏
            supplyOfGoodsTvCollect.setText(R.string.collection);
            supplyOfGoodsTvCollect.setCompoundDrawables(getIdDrawable(R.mipmap.icon_collect_normal), null, null, null);
        }
    }

    /**
     * 更新banner显示
     * 作者：gassion on 17/8/16 23:31
     * 最可怕的敌人，就是没有坚强的信念。
     */
    private void updateBannerView(final List<String> stringList) {
        int screenWidth = DimenUtils.getWindowsWidth(this) - DimenUtils.dip2px(16);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, screenWidth / 2);
        viewFeedBannerInner.setLayoutParams(params);
        goodsBannerLayout.setRootView(view);
        goodsBannerLayout.setVisibility(View.VISIBLE, DimenUtils.dp2px(20));
        goodsBannerLayout.setPagerAdapter(new BannerViewPager.BannerViewPagerAdapter() {
            @Override
            public int bannerImageCount() {
                return stringList.size();
            }

            @Override
            public String bannerImageUrlAtIndex(int index) {
                return stringList.get(index);
            }

            @Override
            public void bannerDidSelectAtIndex(int index) {
                Intent intent = new Intent(PublishedSourcesDetailActivity.this, ImagePagerActivity.class);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (ArrayList)stringList);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, index);
                startActivity(intent);
            }
        });
    }

    @OnClick({R.id.layout_back, R.id.supply_of_goods_layout_collect, R.id.supply_of_goods_tv_leave_a_message, R.id.supply_of_goods_tv_send_message, R.id.supply_of_goods_ll_personal_details, R.id.layout_right_share})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.supply_of_goods_layout_collect:
                if (mResponseData.isCollection()) {
                    requestCancelCollectionData();
                } else {
                    requestCollectionData();
                }
                break;

            case R.id.supply_of_goods_tv_send_message:
                intent = new Intent(PublishedSourcesDetailActivity.this, ChatActivity.class);
                intent.putExtra(ChatConstant.EXTRA_USER_ID, supplier_info.getUid());//传递用户的唯一id
                intent.putExtra(ChatConstant.EXTRA_USER_NICK_NAME, supplier_info.getName());//传递用户的唯一id
                intent.putExtra(ChatConstant.EXTRA_USER_AVATAR, supplier_info.getAvatar());
                startActivity(intent);
                break;

            case R.id.supply_of_goods_tv_leave_a_message:
                sendMessage();
                break;

            case R.id.supply_of_goods_ll_personal_details:
                intent = new Intent(PublishedSourcesDetailActivity.this, MerchantsHomePageActivity.class);
                intent.putExtra(MerchantsHomePageActivity.PUBLISH_UID, supplier_info.getUid());
                startActivity(intent);
                break;

            case R.id.layout_right_share:
                List<String> stringList = super.strConvertList(publish_info.getPic());
                new BottomDialog(PublishedSourcesDetailActivity.this)
                        .toShareParams(publish_info.getName(), publish_info.getShareUrl(), stringList.get(0),
                                publish_info.getContent()).show();
                break;
        }
    }

    /**
     * 取消收藏
     */
    private void requestCancelCollectionData() {
        showWaiting();
        String url = NetworkConstants.CANCLE_COLLECTION_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("collection_id", mResponseData.getIs_collectionis());
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MY_COLLECTION));
                    mResponseData.setIs_collectionis("0");
                    updateCollectUI(mResponseData);
                } else {
                    showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 收藏
     */
    private void requestCollectionData() {
        showWaiting();
        String url = NetworkConstants.COLLECTION_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("type", "1");
        params.put("product_id", publish_info.getId());
        params.put("uid", Global.user.getUid());
        GsonRequest<CommonListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                CommonListDataResponse.class, false, params, new Response.Listener<CommonListDataResponse>() {
            @Override
            public void onResponse(CommonListDataResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MY_COLLECTION));
                    List<String> responseData = response.getData();
                    for (int i = 0; i < responseData.size(); i++) {
                        mResponseData.setIs_collectionis(responseData.get(i));
                    }
                    updateCollectUI(mResponseData);
                } else {
                    showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    @Override
    protected void emptyOnclick() {
        emptyView.bind();
        requestData();
    }

    /**
     * 发布留言
     */
    private void sendMessage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveEditButton(getString(R.string.confirm), new AlertDialog.OnClickEditListener() {
            @Override
            public void onClick(DialogInterface dialog, String content) {
                requestAddMessageData(content);
            }
        });
        AlertDialog mDialog = builder.create();
        mDialog.setCancelable(false);
        mDialog.show();
    }


    /**
     * 发布留言
     */
    private void requestAddMessageData(String content) {
        showWaiting();
        String url = NetworkConstants.ADD_MESSAGE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("business_uid", publish_info.getUid());
        params.put("publish_id", publish_info.getId());
        params.put("content", content);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissWaiting();
                showToast(response.getMsg());
                if (response.isSuccess()) {
                    requestData();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    @Override
    public void onResume() {
        super.onResume();
        dismissWaiting();
    }

}
